'use strict';

const moment = require('moment');
const async = require('async');

const Controller = require('../../../core/common');

class UserGoodsController extends Controller {
  async index() {
    const { ctx, app } = this;

    const { status = 0 } = ctx.request.query;

    const attributes = ['id', 'createdAt', 'updatedAt'];
    const goodsPrizesAttributes = ['id', 'title'];
    const throughWhere = {};
    status && Object.assign(throughWhere, { status });
    const data = await ctx.service.v1.userGoods.findAll({ attributes, goodsPrizesAttributes, throughWhere });

    this.success(data);
  }

  // 详情页参与抽奖
  async create() {
    const { ctx, app } = this;

    const { userId, goodsId, goodsPrizeId, number = 1 } = ctx.request.body;
    const goodsResults = await ctx.model.Goods.findOne({ where: { id: goodsId } }) || {};
    if (!goodsResults.id) return this.success(null, '奖品不存在', -1);
    if (goodsResults.status !== 0) return this.success(null, '抽奖已结束', -1);
    // 按时间抽奖
    if (goodsResults.style === 0) {

      return this.success();
    }
    // 按人数抽奖
    if (goodsResults.style === 1) {
      const maxNum = await app.redis.get('goods').get(`goodsUsers_maxNum_${goodsId}`) || 0;
      const curNum = await app.redis.get('goods').get(`goodsUsers_curNum_${goodsId}`) || 0;
      if (curNum === maxNum) {
        // 更改抽奖用户为中奖用户
        const usersArray = await ctx.model.UsersGoods.findAll({
          attributes: ['userId'],
          where: { goodsId, goodsPrizeId },
          order: [
            ['number', 'DESC']
          ],
          limit: maxNum
        });
        async.each(usersArray, async (item, callback) => {
          await ctx.model.UsersGoods.update({ status: 2 }, { where: { goodsId, goodsPrizeId, userId: item.userId } });
          callback(null);
        });
        await app.model.Goods.update({ status: 1 }, { where: { id: goodsId } });
      }
      // 获取抽奖的参与用户数
      // const goodsNum = await ctx.model.UsersGoods.count({ where: { goodsId, goodsPrizeId } });
      // if (goodsResults.style === 1 && goodsResults.status === 0 && goodsResults.number <= goodsNum) {
      //   // 查找中奖用户&&更改状态为已中奖
      //   await ctx.model.query(
      //     `UPDATE UsersGoods SET status = 2 
      //     WHERE id = (SELECT id FROM (SELECT id FROM UsersGoods WHERE userId = '${userId}' AND goodsId = '${goodsId}' AND goodsPrizeId = '${goodsPrizeId}' 
      //     ORDER BY number DESC LIMIT ${goodsResults.number}) AS ids)
      //   `
      //   )
      //   const max = await ctx.model.GoodsUsers.max('number', { where: { userId, goodsId: id, goodsPrizeId } })
      //   await ctx.model.Goods.update({ status: 1 }, { where: { id }, });
      // }

      // 查用户的幸运草数量
      const integrals = await ctx.model.Integrals.findOne({
        attributes: ['amount'],
        order: [
          ['id', 'DESC']
        ],
        where: { userId }
      });

      // 种草
      if (integrals && (integrals.get('amount') > number)) {
        // 查用户的种草总数量
        const integralOuts = await ctx.model.IntegralOuts.findOne({
          attributes: ['total'],
          order: [
            ['id', 'DESC']
          ],
          where: { userId }
        });

        const current = moment().format('YYYY-MM-DD hh:mm:ss');
        const where = { userId, goodsId, goodsPrizeId };
        const data = await ctx.model.UsersGoods.findOrCreate({
          defaults: {
            goodsId,
            goodsPrizeId,
            status: 0,
            number,
            createdAt: current,
            updatedAt: current
          },
          where
        });
        if (data && data.pop()) {
          // 记录奖品人数
          await app.redis.get('goods').incr(`goodsUsers_curNum_${goodsId}`);
          await ctx.model.IntegralOuts.create({
            userId,
            goodsId,
            total: integralOuts ? integralOuts.get('total') + number : number,
            number,
            type: 0,
            createdAt: current,
            updatedAt: current,
          });
        };
        if (data && !data.pop()) {
          await ctx.model.UsersGoods.update({ number: data[0].number + number }, { where })
        };
        return this.success(null, '参与抽奖成功！');
      }
    } else {
      return this.success(null, '幸运草数量不足', -1);
    }

    this.success(null, '不清楚你在做什么', -1);
  }
}

module.exports = UserGoodsController;